---
import { getCollection } from 'astro:content';
import type { GetStaticPathsOptions } from 'astro';
import Main from '@/layouts/Main.astro';
import Layout from '@/layouts/Layout.astro';
import Header from '@/components/Header.astro';
import Footer from '@/components/Footer.astro';
import Card from '@/components/Card.astro';
import Pagination from '@/components/Pagination.astro';
import getUniqueTags from '@/utils/getTags';
import config from '@/config';
import { getPostsByTag } from '@/utils/getPosts';

export async function getStaticPaths({ paginate }: GetStaticPathsOptions) {
  const posts = await getCollection('blog');
  const tags = getUniqueTags(posts);

  return tags.flatMap(({ tag, tagName }) => {
    const tagPosts = getPostsByTag(posts, tag);

    return paginate(tagPosts, {
      params: { tag },
      props: { tagName },
      pageSize: config.postPageSize,
    });
  });
}

const params = Astro.params;
const { tag } = params;
const { page, tagName } = Astro.props;
---

<Layout title={`Tag: ${tagName} | ${config.title}`}>
  <Header />
  <Main pageTitle={[`Tag:`, `${tagName}`]} titleTransition={tag}>
    <h1 slot="title" transition:name={tag}>{`Tag:${tag}`}</h1>
    <ul>
      {page.data.map(data => <Card {...data} excerpt={false} />)}
    </ul>
  </Main>

  <Pagination {page} />

  <Footer noMarginTop={page.lastPage > 1} />
</Layout>
